package com.it.jzs.controller.admin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.it.jzs.pojo.Type;
import com.it.jzs.service.admin.AdminTypeService;
import com.it.jzs.vo.Result;
import com.it.jzs.vo.params.PageParms;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("admin")
public class AdminTypeController {
    @Resource
    private AdminTypeService adminTypeService;

    @Value("${file.ip}")
    private String ip;

    @GetMapping("type")
    public Result<Object> ListTypePage(@RequestParam("index") Integer index, @RequestParam("size") Integer size, @RequestParam("keyWords") String keyWords) {  // 分页查询
        Result<Object> result = adminTypeService.selectPage(index, size, keyWords);
        return result;
    }

    @PostMapping("type")
    public Result<Type> addType(@RequestBody Type type) {  // 新增
        adminTypeService.insertOne(type);
        return Result.success(null, "success");
    }

    @DeleteMapping("type/{id}")
    public Result<Object> deleteType(@PathVariable("id") Integer id) {  // 删除分类
        Result<Object> result = adminTypeService.delete(id);
        return result;
    }

    @PutMapping("type")
    public Result<Object> updateType(@RequestBody Type type) {
        Result<Object> result = adminTypeService.update(type);
        return result;
    }

    @PostMapping("type/upload")
    public Result<String> upload(MultipartFile file) throws IOException { // 分类图片上传接口
        String originalFilename = file.getOriginalFilename();// 获取上传的文件名
        int i = originalFilename.lastIndexOf("."); // 查看最后一个出现.的位置
        String houzui = originalFilename.substring(i);  // 截取 这个索引开始也就是.开始的后缀
        UUID uuid = UUID.randomUUID();
        StringBuilder builder = new StringBuilder();
        builder.append(uuid).append(houzui);  // 减少因为字符串的拼接消耗的性能  拼接的文件名
        String rootFilePath = "E:\\upload01\\" + builder.toString();
        File file1 = FileUtil.writeBytes(file.getBytes(), rootFilePath);
//         正常来说应该是由后端返回拼接好的图片地址
        return Result.success(new String(builder.toString()), "上传成功");
    }

    @GetMapping("type/all")
    public Result<Object> selectAllType() {
        Result<Object> result = adminTypeService.findAll();
        return result;
    }


    @GetMapping("type/addblog")   // 这个接口用来专门获取 新增博客的时候所需要的的回显数据
    public Result<Object> selectAddBlogVo() {
        Result<Object> result = adminTypeService.findAddBlogTypeVo();
        return result;
    }

    @PostMapping("type/deletebatch")
    public Result<Object> deleteBatch(@RequestBody List<Integer> ids) {  // 批量删除
        Result<Object> result = adminTypeService.deleteBatch(ids);

        return result;
    }
}